package com.lxz.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxz.usercenter.common.BaseResponse;
import com.lxz.usercenter.common.ErrorCode;
import com.lxz.usercenter.common.ResultUtils;
import com.lxz.usercenter.constant.UserConstant;
import com.lxz.usercenter.exception.BusinessException;
import com.lxz.usercenter.model.domain.User;
import com.lxz.usercenter.model.request.UserLoginRequest;
import com.lxz.usercenter.model.request.UserRegisterRequest;
import com.lxz.usercenter.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
@Api(value = "用户相关接口", tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        log.info("userRegisterRequest:{}", userRegisterRequest);
        if (userRegisterRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数错误", "");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long l = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(l);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        log.info("用户登录:{}", userLoginRequest);
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数错误", "");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数错误", "");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }


    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogin(HttpServletRequest request) {
        log.info("用户注销:{}", request);
        if (request == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数错误", "");
        }
        int i = userService.userLogout(request);
        return ResultUtils.success(i);
    }


    /**
     * 更新用户信息
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        log.info("更新用户:{}", user);
        if (user == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getCurrentUser(request);
        int result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    @GetMapping("/query")
    public BaseResponse<List<User>> queryUser(String username, HttpServletRequest request) {
        log.info("查询用户:{}", username);
        if (!userService.isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限操作", "");
        }
        //查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }


    /**
     * 推荐用户
     * @param request
     * @return
     */
    /**
     * 推荐页面
     *
     * @param request
     * @return
     */

    @GetMapping("/recommend")
    public BaseResponse<List<User>> commendUsers(HttpServletRequest request) {
        log.info("推荐用户:{}", request);
        ValueOperations<String, Object> ValueOperations = redisTemplate.opsForValue();

        //查询是否有缓存
        User currentUser = userService.getCurrentUser(request);
        String userId = String.valueOf(currentUser.getId());
        String redisKey = String.format("yupao:user:recommend:%s", userId);

        List<User> userList = (List<User>) ValueOperations.get(redisKey);
        //如果有缓存就读缓存
        if (userList != null) {
            return ResultUtils.success(userList);
        }

        //如果没有缓存就查询数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        //存入缓存
        try {
            ValueOperations.set(redisKey, list, 10, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis存储异常", e);
        }
        return ResultUtils.success(list);
    }


    /**
     * 根据用户id删除用户
     *
     * @param id
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        log.info("删除用户:{}", id);
        if (!userService.isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限操作", "");
        }
        if (id <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数错误", "");
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }


    /**
     * 获取当前登录用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User current_user = (User) userObj;
        if (current_user == null) {
            return null;
        }
        //TODO:判断用户是否合法
        Long userId = current_user.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }


    /**
     * 根据标签查询用户
     *
     * @param tagNameList
     * @return
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUserByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        log.info("查询用户:{}", tagNameList);
        List<User> userList = userService.searchUserByTags(tagNameList);
        return ResultUtils.success(userList);
    }


}
